package com.weigang.config;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
//import com.theokanning.openai.completion.CompletionRequest;
//import com.theokanning.openai.service.OpenAiService;
//import org.jetbrains.annotations.NotNull;
//import org.jetbrains.annotations.Nullable;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.model.Model;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class OpenAIService {

    private final RestTemplate restTemplate;
    public OpenAIService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    private OpenAIConfig openAIConfig;


    /**
     * 调用 OpenAI Models 接口
     * @return 返回接口响应内容
     */
    public String getModels() {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + openAIConfig.getApiKey());

        // 封装请求
        HttpEntity<String> entity = new HttpEntity<>(headers);

        // 发送 GET 请求
        ResponseEntity<String> response = restTemplate.exchange(openAIConfig.getApiUrl(), HttpMethod.GET, entity, String.class);
        return response.getBody();
    }

//    public String getCompletion(String prompt) {
//        String url = openAIConfig.getApiUrl();
//        String apiKey = openAIConfig.getApiKey();
//
//        // 构造请求头
//        var headers = new org.springframework.http.HttpHeaders();
//        headers.set("Authorization", "Bearer " + apiKey);
////        headers.set("OpenAI-Organization", "org-v7JL9lPZZsWut7y9yToToS9Z");
////        headers.set("OpenAI-Project", "Bearer " + apiKey);
//        headers.set("Content-Type", "application/json");
//
//        // 构造请求体
//        Map<String, Object> requestBody = new HashMap<>();
//        requestBody.put("model", "GPT-3.5 Turbo");
//        requestBody.put("messages", prompt);
//        requestBody.put("max_tokens", 100);
//        requestBody.put("temperature", 0.7);
//
//        // 包装请求体
//        var request = new org.springframework.http.HttpEntity<>(requestBody, headers);
//
//        // 调用API
//        var response = restTemplate.postForEntity(url, request, Map.class);
//
//        // 解析结果
//        Map<String, Object> responseBody = response.getBody();
//        if (responseBody != null && responseBody.containsKey("choices")) {
//            var choices = (java.util.List<Map<String, Object>>) responseBody.get("choices");
//            if (!choices.isEmpty()) {
//                return (String) choices.get(0).get("text");
//            }
//        }
//        return "No response from OpenAI.";
//    }

    public void getCompletion(String prompt) {
        //        // 构造请求头
        Map<String,String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + openAIConfig.getApiKey());
//        headers.set("OpenAI-Organization", "org-v7JL9lPZZsWut7y9yToToS9Z");
//        headers.set("OpenAI-Project", "Bearer " + apiKey);
        headers.put("Content-Type", "application/json");
        // 构造请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "gpt-3.5-turbo-1106");
        requestBody.put("messages", prompt);
        requestBody.put("max_tokens", 100);
        requestBody.put("temperature", 0.7);
        HttpResponse execute = HttpRequest.get(openAIConfig.getApiUrl()).addHeaders(headers).body(JSONUtil.toJsonStr(requestBody)).execute();
        System.out.println(execute);
        // 打印响应结果
        System.out.println("响应状态码: " + execute.getStatus());
        System.out.println("响应内容: " + execute.body());


    }

    public String askGPT(String question) {
        String url = "https://api.openai.com/v1/chat/completions";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + openAIConfig.getApiKey());
        headers.set("Content-Type", "application/json");
        // 构造请求体
        String requestBody = "{\n" +
                "        \"model\": \"gpt-4o-mini\",\n" +
                "        \"messages\": [\n" +
                "            {\n" +
                "                \"role\": \"system\",\n" +
                "                \"content\": \"You are a helpful assistant.\"\n" +
                "            }" +
//                ",\n" +
//                "            {\n" +
//                "                \"role\": \"user\",\n" +
//                "                \"content\": \"Write a haiku that explains the concept of recursion.\"\n" +
//                "            }\n" +
                "        ]\n" +
                "    }";
//        String requestBody = String.format(
//                "{\n" +
//                        "  \"model\": \"gpt-3.5-turbo-1106\",\n" +
//                        "  \"messages\": [{\"role\": \"user\", \"content\": \"%s\"}],\n" +
//                        "  \"max_tokens\": 100\n" +
//                        "}", question);
        System.out.println(requestBody);
//        String requestBody = """
//            {
//                "model": "gpt-3.5-turbo",
//                "messages": [{"role": "user", "content": "%s"}],
//                "max_tokens": 100
//            }
//            """.formatted(question);

        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
//        try {
            ResponseEntity<String> response = restTemplate.exchange(openAIConfig.getApiUrl(), HttpMethod.POST, entity, String.class);
            return response.getBody();
//        } catch (HttpClientErrorException.TooManyRequests e) {
//            e.printStackTrace();
//            // 如果遇到 429 错误，读取 Retry-After 头并等待指定时间
//            String retryAfter = e.getResponseHeaders().getFirst("Retry-After");
//
//            return "错误！";
//        }

//        OpenAiService service = new OpenAiService(openAIConfig.getApiKey());
//        CompletionRequest completionRequest = CompletionRequest.builder()
//                .model("text-embedding-3-large")
//                .prompt(question)
//                .temperature(0.5)
//                .maxTokens(2048)
//                .topP(1D)
//                .frequencyPenalty(0D)
//                .presencePenalty(0D)
//                .build();
//        for (CompletionChoice completionChoice : service.createCompletion(completionRequest).getChoices()) {
//            System.out.println(completionChoice);
//        }
//        return "";
    }



}
